<template>
  <div class="example1-wrapper">
    <div class="content-layout">
      <!-- 左侧拓扑结构 -->
      <div class="left-tree">
        <div class="tree-title">业务拓扑</div>
        <bk-tree
          ref="topologyTree"
          :data="treeData"
          :lazy="true"
          :load="loadNode"
          @click-node="handleNodeClick"
          :expand-on-click="true"
        ></bk-tree>
      </div>

      <!-- 右侧内容区域 -->
      <div class="right-content">
        <div class="fr clearfix mb15">
          <bk-form form-type="inline">
            <bk-form-item label="业务">
              <bk-select
                :disabled="false"
                v-model="biz_id"
                style="width: 250px;"
                ext-cls="select-custom"
                @change="bizChangeCallback"
                ext-popover-cls="select-popover-custom"
                searchable
              >
                <bk-option
                  v-for="item in biz_list"
                  :key="item.bk_biz_id"
                  :id="item.bk_biz_id"
                  :name="item.bk_biz_name"
                />
              </bk-select>
            </bk-form-item>
            <bk-form-item label="集群">
              <bk-select
                v-model="set_id"
                :disabled="false"
                style="width: 250px;"
                ext-cls="select-custom"
                @change="setChangeCallback"
                ext-popover-cls="select-popover-custom"
                searchable
              >
                <bk-option
                  v-for="item in set_list"
                  :key="item.bk_set_id"
                  :id="item.bk_set_id"
                  :name="item.bk_set_name"
                />
              </bk-select>
            </bk-form-item>
            <bk-form-item label="模块">
              <bk-select
                v-model="module_id"
                :disabled="false"
                style="width: 250px;"
                ext-cls="select-custom"
                @change="moduleChangeCallback"
                ext-popover-cls="select-popover-custom"
                searchable
              >
                <bk-option
                  v-for="item in module_list"
                  :key="item.bk_module_id"
                  :id="item.bk_module_id"
                  :name="item.bk_module_name"
                />
              </bk-select>
            </bk-form-item>
            <bk-form-item>
              <bk-button theme="primary" title="提交" @click="searchHosts">搜索</bk-button>
            </bk-form-item>
          </bk-form>
        </div>

        <bk-table
          style="margin-top: 15px;"
          :data="paginatedData"
          :size="size"
          :pagination="pagination"
          @page-change="handlePageChange"
          @page-limit-change="handleSizeChange"
        >
          <bk-table-column label="主机ID" prop="bk_host_id" />
          <bk-table-column label="主机IP" prop="bk_host_innerip" />
          <bk-table-column label="操作人" prop="operator" />
          <bk-table-column label="备份维护人" prop="bk_backup_operator" />
          <bk-table-column label="操作">
            <template slot-scope="props">
              <bk-button
                theme="primary"
                text
                :disabled="props.row.status === '创建中'"
                @click="getHostDetail(props.row.bk_host_id)"
              >
                查看详情
              </bk-button>
            </template>
          </bk-table-column>
        </bk-table>

        <bk-sideslider
          class="bk-layout-component-nelgpjna sideslider1e5ab"
          :is-show.sync="isSidesliderShow"
          :title="'主机详情'"
          :show-mask="false"
          :width="600"
          direction="right"
        >
          <template slot="content">
            <div class="step-detail-container">
              <div
                class="step-detail-item"
                v-for="item in host_detail"
                :key="item.bk_property_id"
              >
                <strong>{{ item.bk_property_name + '：' }}</strong>
                <span>{{ item.bk_property_value ? item.bk_property_value : '无' }}</span>
              </div>
            </div>
          </template>
        </bk-sideslider>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Example1View',
  components: {},
  data() {
    return {
      size: 'small',
      formData: {
        name: '',
        date: '',
      },
      tableData: [],
      biz_list: [],
      biz_id: null,
      set_list: [],
      set_id: null,
      module_list: [],
      module_id: null,
      allHostList: [], // 存储所有查询到的主机数据
      host_list: [], // 用于显示的当前页数据
      operator: null,
      bak_operator: null,
      host_detail: [],
      isSidesliderShow: false,
      pagination: {
        current: 1,
        count: 0,
        limit: 10,
        limitList: [10, 20, 50, 100], // 每页显示条数选项
        showLimit: true, // 显示每页条数选择器
        showTotalCount: true // 显示总数
      },
      treeData: [], // 拓扑树数据
      isLoadingTree: false
    };
  },
  computed: {
    // 计算当前页数据
    paginatedData() {
      const start = (this.pagination.current - 1) * this.pagination.limit;
      const end = start + this.pagination.limit;
      return this.allHostList.slice(start, end);
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.getBizData();
      this.buildTopologyTree();
    },
    async getTableData() {
      try {
        const res = await this.$store.dispatch('example/getTableData', {}, { fromCache: true });
        this.tableData = res.data.list;
        this.pagination.count = res.data.list.length;
      } catch (e) {
        console.error(e);
      }
    },
    async getBizData() {
      try {
        const response = await this.$store.dispatch('example/getBizData', {}, {fromCache: true});
        this.biz_list = response.data.info;
      } catch (e) {
        console.error(e);
      }
    },
    async getSetData() {
      try {
        const response = await this.$store.dispatch(
          'example/getSetData',
          { bk_biz_id: this.biz_id },
          { fromCache: true }
        );
        this.set_list = response.data.info;
      } catch (e) {
        console.error(e);
      }
    },
    async getModuleData() {
      try {
        const response = await this.$store.dispatch(
          'example/getModuleData',
          {
            bk_biz_id: this.biz_id,
            bk_set_id: this.set_id
          },
          { fromCache: true }
        );
        this.module_list = response.data.info;
      } catch (e) {
        console.error(e);
      }
    },
    async searchHosts() {
      try {
        const params = { bk_biz_id: this.biz_id };
        if (this.set_id) {
          params.bk_set_id = this.set_id;
        }
        if (this.module_id) {
          params.bk_module_id = this.module_id;
        }
        if (this.operator) {
          params.operator = this.operator;
        }
        const response = await this.$store.dispatch(
            "example/getHostData",
            params,
            {fromCache: true}
        );
        // 保存所有数据
        this.allHostList = response.data.info || [];
        // 更新分页信息
        this.pagination.count = this.allHostList.length;
        this.pagination.current = 1; // 搜索时重置为第一页
      } catch (e) {
        console.error(e);
      }
    },
    async loadNode(node, resolve) {
      const { id, level } = node;

      // 检查缓存
      if (this.cache[id]) {
        resolve(this.cache[id]);
        return;
      }

      try {
        let children = [];
        if (level === 'biz') {
          const response = await this.$store.dispatch('example/getSetData', { bk_biz_id: id });
          children = response.data.info.map(set => ({
            id: set.bk_set_id,
            name: set.bk_set_name,
            level: 'set',
            isLeaf: false,
          }));
        } else if (level === 'set') {
          const response = await this.$store.dispatch('example/getModuleData', { bk_set_id: id });
          children = response.data.info.map(module => ({
            id: module.bk_module_id,
            name: module.bk_module_name,
            level: 'module',
            isLeaf: true,
          }));
        }

        // 缓存数据
        this.cache[id] = children;
        resolve(children);
      } catch (error) {
        console.error('加载节点失败:', error);
        resolve([]);
      }
    },
    handleNodeClick(node) {
      if (node.level === 'module') {
        this.biz_id = node.bizId;
        this.set_id = node.setId;
        this.module_id = node.moduleId;
        this.searchHosts();
      }
    },
    async getHostDetail(bkHostId) {
      try {
        const response = await this.$store.dispatch(
            "example/getHostDetail",
            {bk_host_id: bkHostId},
            {fromCache: true}
        );
        this.host_detail = response.data;
        this.isSidesliderShow = true;
      } catch (e) {
        console.error(e);
      }
    },
    bizChangeCallback(newValue) {
      this.biz_id = newValue;
      this.set_id = null;
      this.module_id = null;
      // Fixed bug: 当业务下拉框修改时设置集群为空，导致触发空值回调，无故修改模块下拉框
      this.module_list = [];
      if (newValue != null) this.getSetData();
    },
    setChangeCallback(newValue) {
      this.set_id = newValue;
      this.module_id = null;
      if (newValue != null) this.getModuleData();
    },
    moduleChangeCallback(newValue) {
      this.module_id = newValue;
    },
    toggleTableSize() {
      const size = ['small', 'medium', 'large'];
      const index = (size.indexOf(this.size) + 1) % 3;
      this.size = size[index];
    },
    handlePageChange(page) {
      this.pagination.current = page;
    },
    handleSizeChange(limit) {
      this.pagination.limit = limit;
      this.pagination.current = 1; // 切换每页显示条数时，重置为第一页
    },
    remove(row) {
      const index = this.allHostList.indexOf(row);
      if (index !== -1) {
        this.allHostList.splice(index, 1);
        this.pagination.count = this.allHostList.length;
      }
    },
    reset(row) {
      // eslint-disable-next-line no-param-reassign
      row.status = '创建中';
    },
    // 构建拓扑树
    async buildTopologyTree() {
      this.isLoadingTree = true;
      try {
        // 获取业务列表
        await this.getBizData();

        // 构建树结构
        this.treeData = [];
        for (const biz of this.biz_list) {
          const bizNode = {
            id: `biz-${biz.bk_biz_id}`,
            name: biz.bk_biz_name,
            level: 'biz',
            bizId: biz.bk_biz_id,
            children: [],
            isOpen: false
          };

          // 获取该业务下的集群列表
          const setResponse = await this.$store.dispatch(
              'example/getSetData',
              {bk_biz_id: biz.bk_biz_id},
              {fromCache: true}
          );
          const sets = setResponse.data.info || [];

          for (const set of sets) {
            const setNode = {
              id: `set-${set.bk_set_id}`,
              name: set.bk_set_name,
              level: 'set',
              bizId: biz.bk_biz_id,
              setId: set.bk_set_id,
              children: [],
              isOpen: false
            };

            // 获取该集群下的模块列表
            const moduleResponse = await this.$store.dispatch(
                'example/getModuleData',
                {
                  bk_biz_id: biz.bk_biz_id,
                  bk_set_id: set.bk_set_id
                },
                {fromCache: true}
            );
            const modules = moduleResponse.data.info || [];

            for (const module of modules) {
              setNode.children.push({
                id: `module-${module.bk_module_id}`,
                name: module.bk_module_name,
                level: 'module',
                bizId: biz.bk_biz_id,
                setId: set.bk_set_id,
                moduleId: module.bk_module_id
              });
            }

            bizNode.children.push(setNode);
          }

          this.treeData.push(bizNode);
        }
      } catch (e) {
        console.error('构建拓扑树失败:', e);
        this.$bkMessage({
          theme: 'error',
          message: '加载拓扑结构失败'
        });
      } finally {
        this.isLoadingTree = false;
      }
    },
    // 处理节点点击事件
    handleNodeClick(node) {
      if (node.level === 'module') {
        // 设置表单值
        this.biz_id = node.bizId;
        this.bizChangeCallback(node.bizId);

        // 需要等待集群数据获取完成
        setTimeout(() => {
          this.set_id = node.setId;
          this.setChangeCallback(node.setId);

          // 需要等待模块数据获取完成
          setTimeout(() => {
            this.module_id = node.moduleId;
            // 自动执行搜索
            this.searchHosts();
          }, 300);
        }, 300);
      }
    }
  },
};
</script>

<style scoped>
.example1-wrapper {
  height: 100%;
}

.content-layout {
  display: flex;
  height: calc(100vh - 200px);
}

.left-tree {
  width: 240px;
  border-right: 1px solid #dcdee5;
  padding: 10px;
  overflow: auto;
  background-color: #f5f7fa;
}

.tree-title {
  font-size: 14px;
  font-weight: bold;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}

.right-content {
  flex: 1;
  padding: 0 10px;
  overflow: auto;
}
</style>
